﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockFinder.Model;
using System.Net;
using System.IO;
using log4net;
using StockFinder.Model.Enumerations;

namespace StockFinder.Services.Extractors.Symbols
{
    /// <summary>
    /// Extracts the list of symbols currently listed on Nasdaq
    /// </summary>
    public class NasdaqSymbolListExtractor
    {
        private static readonly ILog _Log = LogManager.GetLogger(typeof(NasdaqSymbolListExtractor)); 

        /*
         * Nasdaq is pretty simple, there is a download link that downloads CSV file of all symbols listed on that date         
         * */

        const string INDEX_URL = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download";
        const string EXCHANGE = "NASDAQ";

        public List<Symbol> GetSymbols()
        {
            var symbolList = new List<Symbol>();

            //create webrequest from url
            HttpWebRequest webRequest = HttpWebRequest.Create(INDEX_URL) as HttpWebRequest;

            HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;

            string pageSource = null;

            //create the reader to extract the page source
            using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
            {
                //get the page source
                pageSource = streamReader.ReadToEnd();
            }

            if (string.IsNullOrEmpty(pageSource))
            {
                _Log.Error("Returned empty string from reading pagesource");
            }
            else
            {
                string[] lines = pageSource.Split(new char[] { Environment.NewLine.ToCharArray()[0] });
                string symbol = string.Empty;

                foreach (string line in lines)
                {
                    string[] fields = line.Split(new char[] { ',' });

                    try
                    {
                        symbol = fields[0].Replace("\"","").Replace("\n","");
                        
                        symbolList.Add(new Symbol()
                        {
                            Name = symbol,
                            Exchange = Exchange.NASDAQ
                        });
                    }
                    catch (Exception exception)
                    {
                        _Log.Error(exception.ToString());
                    }
                }
            }

            webResponse = null;
            webRequest = null;

            return symbolList;
        }
    }
}
